<template>
  <div>
    <el-select @change="select" v-model="getStatus" size="mini" style="width:100%;">
      <el-option
          v-for="(item,index) in PersonnelStatus"
          :key="index"
          :label="item.itemText"
          :value="item.uuid">
      </el-option>
    </el-select>
    <div class="btn_group">
      <we-button size="mini" :type="isShow==1?'primary':''" class="btn_item" @click="isShow = 1"
      >机构树
      </we-button>
      <we-button size="mini" :type="isShow==2?'primary':''" class="btn_item" @click="isShow = 2"
      >常用条件
      </we-button>
      <we-button size="mini" :type="isShow==3?'primary':''" class="btn_item" @click="isShow = 3"
      >固定条件
      </we-button>
    </div>
    <Card v-if="isShow === 1">
      <template slot="title">
        <el-input
            size="mini"
            placeholder="输入关键字进行过滤"
            v-model="filterText"
        >
        </el-input>
      </template>
      <template slot="content">
        <el-tree
            class="department-tree"
            :data="data"
            :props="defaultProps"
            highlight-current
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            @node-click="handleTreeNodeClick"
            style="height:600px;overflow:auto"
            ref="tree"
        >
          <template slot-scope="{ data }">
            <el-popover
                popper-class="popover"
                size="mini"
                placement="right"
                :visible-arrow="false"
                trigger="hover"
                :content="data.name"
            >
            <span class="show-ellipsis" slot="reference">
              {{ data.name ? data.name.substr(0, 11) : '-' }}
            </span>
            </el-popover>
          </template>
        </el-tree>
      </template>
    </Card>
    <div class="sql_tree" v-if="isShow === 2">
      <div class="sql_item">
        <div class="flex_bet">
          <span class="sql_type">机构范围</span>
          <we-button @click="selectInstitutions = true" size="mini" style="height:auto;min-width:50px;margin:0"
          >选择
          </we-button>
        </div>
        <el-input
            type="textarea"
            v-model="textarea"
            disabled
            :rows="3"
        >
        </el-input>
      </div>
      <div class="sql_item">
        <div class="flex_bet">
          <span class="sql_type">年龄</span>
        </div>
        <div class="border_line">
          <div>
            <el-select v-model="age1" filterable clearable placeholder="" size="mini" class="mini_select">
              <el-option v-for="num in 100"
                         :key="num"
                         :label="num"
                         :value="num">
              </el-option>
            </el-select>
            <span style="margin:0 7px;">至</span>
            <el-select v-model="age2" filterable clearable placeholder="" size="mini" class="mini_select">
              <el-option v-for="num in 100"
                         :key="num"
                         :label="num"
                         :value="num">
              </el-option>
            </el-select>
            <span style="margin:0 7px;">岁</span>
            <el-select v-model="gender" clearable placeholder="" size="mini" class="mini_select">
              <el-option v-for="item in sexDict" :key="item.uuid"
                         :label="item.name"
                         :value="item.uuid"></el-option>
            </el-select>
          </div>
          <div style="margin-left:7px;margin-top:5px;">
            <!-- <el-checkbox-group v-model="checkList">
              <el-checkbox label="少数民族"></el-checkbox>
              <el-checkbox label="非中共党员"></el-checkbox>
            </el-checkbox-group> -->
            <el-checkbox v-model="national">少数民族</el-checkbox>
            <el-checkbox v-model="isNoPartyMember">非中共党员</el-checkbox>
          </div>
        </div>
      </div>
      <div class="sql_item">
        <div class="flex_bet">
          <span class="sql_type">职务类别</span>
        </div>
        <div class="border_line">
          <div>
            <span class="ft13">职务级别 </span>
            <el-select placeholder="请选择" clearable v-model="isPositionLevel" size="mini" style="width:150px">
              <el-option v-for="item in positionLevel" :key="item.uuid" :label="item.name"
                         :value="item.uuid"></el-option>
            </el-select>
          </div>
          <div style="margin-top:8px">
            <span class="ft13">职务类别 </span>
            <el-select placeholder="请选择" clearable v-model="isJobCategory" size="mini" style="width:150px">
              <el-option v-for="item in jobCategory" :key="item.uuid" :label="item.name" :value="item.uuid"></el-option>
            </el-select>
          </div>
        </div>
      </div>
      <div class="sql_item">
        <div class="flex_bet">
          <span class="sql_type">学历</span>
        </div>
        <div class="border_line" style="padding-bottom:5px;">
          <div>
            <span class="ft13" style="margin-right:5px;">从</span>
            <el-cascader
                clearable
                style="width:150px"
                size="mini"
                placeholder="请选择"
                v-model="educationUp"
                :props="{ value: 'uuid', label: 'name',expandTrigger: 'hover' }"
                :options="recordRange"
            ></el-cascader>
          </div>
          <div style="margin-top:10px;">
            <span class="ft13" style="margin-right:5px;">至</span>
            <el-cascader
                clearable
                style="width:150px"
                size="mini"
                placeholder="请选择"
                v-model="educationDown"
                :props="{ value: 'uuid', label: 'name',expandTrigger: 'hover' }"
                :options="recordRange"
            ></el-cascader>
            <el-checkbox style="margin-top:5px;margin-left:100px;" v-model="fullTime">全日制</el-checkbox>
          </div>
        </div>
      </div>
      <div style="text-align:center;margin:10px 0 10px">
        <span class="ft13">年龄年限计算截止 </span>
        <el-input
            class="schedule"
            style="width:100px"
            @blur="blurCheck"
            v-model="upperAge"
        >
        </el-input>
      </div>
      <div style="margin-bottom:10px">
        <we-button size="mini" style="height:auto;min-width:50px;" @click="deleteBox"
        >清除条件
        </we-button>
        <we-button size="mini" style="height:auto;min-width:50px;" @click="saveBox"
        >保存条件
        </we-button>
        <we-button size="mini" style="height:auto;min-width:50px;" @click="isShow = 3"
        >更多条件
        </we-button>
      </div>
      <div style="border-top:1px solid #ddd">
        <we-button size="mini" @click="startSql" style="height:auto;min-width:100px;margin:10px 0 10px 50px"
        >开始查询
        </we-button>
      </div>
      <div style="white-space:nowrap;width:100px;">
        <el-radio-group v-model="radio">
          <el-radio :label="3" class="radio_item">全库中查</el-radio>
          <el-radio :label="6" class="radio_item">结果中查</el-radio>
          <el-radio :label="9" class="radio_item">追加查询</el-radio>
        </el-radio-group>
      </div>
    </div>

    <div class="select_tree" style="padding-top: 20px" v-if="isShow === 3">
      <el-tree :data="conditionList"
               ref="fixedCondition"
               :props="defaultProps"
               :render-content="renderContent"
               node-key="uuid"
               default-expand-all
               highlight-current
               @node-click="handleNodeClick"
               style="max-height:580px;overflow-y: auto"
               ></el-tree>
      <div style="text-align:center;margin:50px 0 10px">
        <el-input
                class="schedule"
                style="width:170px;"
                @change="startQuery"
                v-model="filterCondition"
                placeholder="过滤条件"
        >
        </el-input>
      </div>
      <div style="text-align:center;margin:10px 0 10px">
        <el-dropdown trigger="click" @command="addFixedCondition">
          <we-button size="mini" style="height:auto;min-width:50px;">添加
          </we-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="0">简单查询</el-dropdown-item>
            <el-dropdown-item command="1">通用查询</el-dropdown-item>
            <el-dropdown-item command="2">复杂查询</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <we-button size="mini" style="height:auto;min-width:50px;" @click="handleNodeClickDelete"
        >删除
        </we-button>
        <we-button size="mini" style="height:auto;min-width:50px;" @click="handleModify"
        >修改
        </we-button>
      </div>
      <el-dialog
              :title="inquireType === 0 ? '简单查询':inquireType === 1 ? '通用查询':'复杂查询'"
              :visible.sync="showQuery"
              :close-on-click-modal="false"
              @close="handleCloseInquire"
              top="10vh"
      >
        <el-row :gutter="10" style="margin-top: 10px">
          <el-col :span="5">
            <div>
              <el-select
                      @change="selectFixedCondition"
                      v-model="subsetUuid"
                      filterable
                      size="mini"
                      style="width: 100%"
              >
                <el-option
                        v-for="(item, index) in fixedConditionList"
                        :key="index"
                        :label="item.name"
                        :value="item"
                >
                </el-option>
              </el-select>
            </div>
            <div class="col_h_b">
              <el-checkbox-group
                      v-model="checkedLeft"
                      @change="handleLeftCheckbox"
                      style="margin-top: 15px"
              >
                <div
                        style="line-height: 20px"
                        v-for="(item, index) in left"
                        :key="index"
                >
                  <el-checkbox
                          :checked="item.checked"
                          :label="item"
                          style="margin-right: 5px"
                  >
                    <img
                            :src="item.type === 'input'
                  ?require('@/assets/img/abc.png'):item.type === 'number'
                  ?require('@/assets/img/123.png'):item.type === 'date'
                  ?require('@/assets/img/calendar.png'):require('@/assets/img/select.png')"
                            style="width: 16px;height: 16px;" alt=""
                    />
                    {{ item.fieldName }}
                  </el-checkbox
                  >
                </div>
              </el-checkbox-group>
            </div>
          </el-col>
          <el-col :span="inquireType === 2?2:4">
            <div style="margin-top: 70px; text-align: center">
              <el-button
                      @click="toRight"
                      type="primary"
                      style="width: 10px"
                      size="small"
              ><em class="el-icon-arrow-right" style="margin: -10px"></em>
              </el-button>
            </div>
            <div style="margin-top: 40px; text-align: center">
              <el-button
                      @click="toLeft"
                      type="primary"
                      style="width: 10px"
                      size="small"
              ><em class="el-icon-arrow-left" style="margin: -10px"></em>
              </el-button>
            </div>
          </el-col>
          <el-col :span="12">
            <div style="border: 1px solid #eee">
              <div style="float: right">
                <we-button type="primary" size="small" @click="toLeft"
                ><em class="el-icon-delete"></em> 删除
                </we-button>
                <we-button type="primary" size="small" @click="delAll"
                ><em class="el-icon-delete-solid"></em> 全部删除
                </we-button>
              </div>
              <div style="margin-top: 10px; clear: both; height: 280px">
                <el-row class="line_h" :gutter="10">
                  <el-col :span="8" style="padding-left: 30px">查询指标项</el-col>
                  <el-col :span="5.2">关系(运算符)</el-col>
                  <el-col :span="9" style="padding-left: 30px">查询值</el-col>
                </el-row>
                <el-checkbox-group v-model="checkedRight" style="height: 240px;overflow-y: auto;">
                  <el-row
                          class="line_h"
                          :gutter="10"
                          v-for="(item, index) in right"
                          :key="index"
                  >
                    <el-col :span="8" class="text_one_row">
                      <el-checkbox
                              class="right-label"
                              :label="item"
                              @change="singleChoice(index,item)"
                              style="margin-right: 5px"
                      >{{ index + 1 }} {{ item.fieldName }}
                      </el-checkbox
                      >
                    </el-col>
                    <el-col style="width: 96px;">
                      <el-select
                              v-model="item.operation"
                              @change="selectSet(index)"
                              :value-key="item.operation"
                              size="mini"
                      >
                        <el-option
                                v-for="i in operationList"
                                :key="i.value"
                                v-if="((item.type === 'number' || item.type === 'date') && i.value !== 'IN' && i.value !== 'NOT_IN'&& i.value !== 'START'
                                    && i.value !== 'NOT_START'&& i.value !== 'END'&& i.value !== 'NOT_END')
                                || ((item.type === 'input' || item.type === 'tree' || item.type === 'radio')
                                    && i.value !== 'LESS_THAN' && i.value !== 'MORE_THAN')"
                                :label="i.label"
                                :value="i.value"
                        >
                        </el-option>
                      </el-select>
                    </el-col>
                    <el-col :span="9" class="text_one_row">
                      <el-input size="mini" v-if="item.type==='input'" v-model="item.value"></el-input>
                      <el-input size="mini" v-if="item.type==='number'" v-model.number="item.value"
                                @blur="leaveJudgment(index)"></el-input>
                      <el-select
                              v-if="item.type === 'radio'"
                              @change="selectSet(index)"
                              v-model="item.value"
                              size="mini"
                      >
                        <el-option
                                v-for="i in item.inquire"
                                :key="i.uuid"
                                :label="i.name"
                                :value="i.uuid"
                        >
                        </el-option>
                      </el-select>
                      <el-cascader
                              v-if="item.type === 'tree'"
                              ref="Company"
                              class="inputW"
                              size="mini"
                              v-model="item.value"
                              :show-all-levels="false"
                              :props="{ value: 'uuid', label: 'name',expandTrigger: 'hover',checkStrictly: true }"
                              :options="item.inquire"
                      ></el-cascader>
                      <el-date-picker
                              v-if="item.type === 'date'"
                              v-model="item.value"
                              size="mini"
                              type="date"
                              class="tate-picker"
                              placeholder="选择日期">
                      </el-date-picker>
                    </el-col>
                  </el-row>
                </el-checkbox-group>

              </div>
              <div v-if="inquireType === 0" class="individual_line">
                <span class="individual_title">条件关系</span>
                <el-radio-group v-model="easyCondition">
                  <div>
                    <el-radio :label="'并且'">并且</el-radio>
                    <el-radio :label="'或者'">或者</el-radio>
                  </div>
                </el-radio-group>
              </div>
              <div v-if="inquireType !== 0">
                <div style="display: flex; justify-content: space-evenly">
                  <we-button @click="createSql(1)" size="small">并且</we-button>
                  <we-button @click="createSql(2)" size="small">或者</we-button>
                  <we-button @click="createSql(3)" size="small">(</we-button>
                  <we-button @click="createSql(4)" size="small">)</we-button>
                </div>
                <div style="margin-top: 10px">
                  <el-input
                      v-model="sqlValue"
                      type="textarea"
                      :autosize="{ minRows: 2, maxRows: 3 }"
                      placeholder="请输入查询逻辑条件
	如:(@1*@2)+@3表示:(@1 或者 @2) 并且 @3"
                  >
                  </el-input>
                </div>
                <div style="margin-top: 10px">
                  <div>表达式解释:</div>
                  <el-input
                      v-model="sqlValueText"
                      type="textarea"
                      :autosize="{ minRows: 2, maxRows: 2 }"
                  >
                  </el-input>
                </div>
              </div>
<!--              <div style="line-height: 50px">-->
<!--                常用统计名称：-->
<!--                <el-input-->
<!--                        size="mini"-->
<!--                        v-model="statisticalName"-->
<!--                        style="width: 75%; margin-left: 5px"-->
<!--                        placeholder="这里输入常用统计名称"-->
<!--                ></el-input>-->
<!--              </div>-->
<!--              <div style="display: flex; justify-content: space-evenly">-->
<!--                <we-button size="small"-->
<!--                ><em class="el-icon-edit-outline"></em> 引入公式-->
<!--                </we-button>-->
<!--                <we-button size="small" @click="confirmationCondition"-->
<!--                ><em class="el-icon-folder-opened"></em> 确认-->
<!--                </we-button>-->
<!--              </div>-->
            </div>
          </el-col>
          <el-col :span="5" v-if="inquireType === 2" style="height: 506px;">
            <div style="height: 340px;text-align: center">
              <we-button @click="handleSaveCondition('save')" size="mini">保存常用条件</we-button>
              <we-button @click="handleImportCondition('import')" size="mini" style="margin-top: 20px">引入常用条件</we-button>
            </div>
            <div
                style="
              color: rgba(102,0,204,1);
              border: 1px solid #eee;
              line-height: 25px;
              text-align: center;
            "
            >
              点击可以引入计算公式：如 年龄、工龄、月份、计算时间等;
              使用公式可以进行更加复杂的查询
            </div>
          </el-col>
        </el-row>
        <div slot="footer" class="dialog-footer">
          <we-button @click="fixedConditionSave" size="mini" type="primary" style="margin-right: 30px"
          >保 存
          </we-button
          >
          <we-button @click="fixedConditionSearch" size="mini" type="primary" style="margin-right: 30px"
          >查 询
          </we-button
          >
          <we-button size="mini" @click="handleCloseInquire">关 闭</we-button>
        </div>
      </el-dialog>

      <el-dialog
              title="固定条件"
              :visible.sync="addFixCondition"
              show-close
              width="500px"
              @close="addFixConditionClose"
      >
        <el-tree
                class="department-tree"
                node-key="uuid"
                :data="data1"
                :render-content="renderContent"
                :props="defaultProps"
                highlight-current
                :check-strictly="true"
                ref="saveStatistics"
        >
        </el-tree>
        <div style="display: flex;margin-top: 20px">
          <div style="width: 120px;">保存名称:</div>
          <el-input placeholder="这里输入名称" size="mini" v-model="saveFixConditionName"></el-input>
        </div>
        <div slot="footer" class="dialog-footer">
          <we-button size="mini" @click="DeleteFixCondition('saveStatistics')">删除</we-button>
          <we-button size="mini" @click="FixConditionConfirm">确认</we-button>
          <we-button size="mini" @click="addFixConditionClose">关闭</we-button>
        </div>
      </el-dialog>
      <el-dialog
          title="常用条件"
          :visible.sync="addCommonlyCondition"
          show-close
          width="500px"
          @close="closeCommonlyCondition"
      >
        <el-tree
            class="department-tree"
            node-key="uuid"
            :data="commonlyList"
            :props="defaultProps"
            highlight-current
            :check-strictly="true"
            ref="saveCommonly"
        >
        </el-tree>
        <div style="display: flex;margin-top: 20px">
          <div style="width: 120px;">常用条件名称:</div>
          <el-input placeholder="这里输入名称" size="mini" v-model="saveCommonlyName"></el-input>
        </div>
        <div slot="footer" class="dialog-footer">
          <we-button v-if="commonlyType === 'import'" size="mini" @click="importCommonly">引入</we-button>
          <we-button v-if="commonlyType === 'save'" size="mini" @click="saveCommonly">保存</we-button>
          <we-button size="mini" @click="DeleteFixCondition('saveCommonly')">删除</we-button>
          <we-button size="mini" @click="closeCommonlyCondition">关闭</we-button>
        </div>
      </el-dialog>
<!--      <el-dialog-->
<!--          title="常用条件查询"-->
<!--          :visible.sync="showQuery222"-->
<!--          width="60%"-->
<!--          :before-close="handleClose">-->
<!--        <el-select @change="selectSubsetUuid" v-model="selectSubset" filterable size="mini" style="width:230px">-->
<!--          <el-option-->
<!--              v-for="item in allSubset"-->
<!--              :key="item.uuid"-->
<!--              :label="item.tableTxt"-->
<!--              :value="item.uuid">-->
<!--          </el-option>-->
<!--        </el-select>-->
<!--        <vue-query-builder :rules="rules" :labels="labels" v-model="query" @input="commonQuery">-->
<!--        </vue-query-builder>-->
<!--        <span slot="footer" class="dialog-footer">-->
<!--        <we-button @click="showQuery = false" type="primary" size="small">取 消</we-button>-->
<!--        <we-button @click="commonQuery" type="primary" size="small">确 定</we-button>-->
<!--      </span>-->
<!--      </el-dialog>-->
    </div>
    <vxe-modal width="360px" v-model="selectInstitutions" title="选择机构范围" size="mini">
      <template v-slot style="border: 1px solid red">
        <div style="text-align: right"><el-checkbox v-model="subordinates">包含下级</el-checkbox></div>
        <div style="width: 340px;max-height: 360px;background-color: #ffffff;overflow-y: auto">
          <el-tree
              node-key="id"
              default-expand-all
              show-checkbox
              :check-strictly="!subordinates"
              class="department-tree"
              :data="data"
              :props="defaultProps"
              :filter-node-method="filterNode"
              ref="TreeRange"
          >
            <template slot-scope="{ data }">
              <el-popover
                  popper-class="popover"
                  size="mini"
                  placement="right"
                  :visible-arrow="false"
                  trigger="hover"
                  :content="data.name"
              >
            <span class="show-ellipsis" slot="reference">
              {{ data.name ? data.name.substr(0, 11) : '-' }}
            </span>
              </el-popover>
            </template>
          </el-tree>
        </div>
        <div style="text-align: center">
          <el-button @click="handleRange" plain  size="mini">确定</el-button>
          <el-button @click="selectInstitutions = false" plain  size="mini">取消</el-button>
        </div>
      </template>
    </vxe-modal>

  </div>
</template>

<script>
import Card from '@/components/Card'
import WeButton from '@/components/WeButton'
import VueQueryBuilder from 'vue-query-builder'
import { bus } from '@/utils/eventBus'
import { getAction, postAction } from '@/api/manage'
import {parseTree} from "@/utils/util";
import {opCondition, opCorePropertyValue, opDictNew, opTableAll, queryCondition} from "@/api/apiUrl";

export default {
  components: {
    Card,
    WeButton,
    VueQueryBuilder
  },
  data () {
    return {
      showQuery: false,
      filterText: '',
      data: [],
      subordinates: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      PersonnelStatus: [], // 人员状态
      getStatus: '',
      fullTime: false,
      recordRange: [],
      educationUp: '',
      educationDown: '',
      textarea: '',
      selectInstitutions: false,
      age1: '',
      age2: '',
      upperAge: '',
      filterCondition: '',
      gender: '',
      isPositionLevel: '', // 职务级别
      isJobCategory: '', // 职务类别
      radio: 3,
      isShow: 1,
      checkList: [],
      departmentId: [],
      national: false, // 少数民族
      isNoPartyMember: false, // 非中共党员
      isEitModify: false, //编辑固定查询
      easyCondition: '并且', //简单查询条件关系
      conditionList: [],
      commonlyList: [],
      data1: [
        {
          uuid: 'null1',
          name: "基本信息类",
          type: 'file',
          children: [],
        },
        {
          uuid: 'null2',
          name: "干部统计类",
          type: 'file',
          children: []
        },
        {
          uuid: 'null3',
          name: "其他类",
          type: 'file',
          children: []
        },
      ],
      queryArray: [],
      str: '',
      rules: [
        {
          type: 'text',
          id: 'vegetable',
          label: '身份证号'
        },
        {
          type: 'numeric',
          id: 'number',
          label: '年龄'
        },
        {
          type: 'select',
          id: 'sex',
          label: '性别',
          choices: [
            {
              label: '男',
              value: '1'
            },
            {
              label: '女',
              value: '2'
            }
          ]
        }
      ],
      labels: {
        matchType: '匹配类型',
        matchTypes: [
          {
            id: 'all',
            label: '全部'
          },
          {
            id: 'any',
            label: '任何'
          }
        ],
        addRule: '添加条件',
        removeRule: '&times;',
        addGroup: '添加分组',
        removeGroup: '&times;',
        textInputPlaceholder: '查询值'
      },
      selectSubset: '', // 选中子集的uuid
      allSubset: [], // 所有子集
      query: {},
      sexDict: [], // 性别
      positionLevel: [], // 职务级别字典
      jobCategory: [], // 职务类别字典
      subsetUuid: '', // 左侧 选中子集的uuid
      fixedConditionList:[],//固定条件子集
      left: [], // 左侧 子集字段数据
      right:[],//右边数据
      checkedLeft: [], // 左侧 选中子集的uuid集合
      checkedRight: [], // 选中右边数据
      sqlValue: "", // 构建出的sql
      commonlyType: "", // 构建出的sql
      sqlValueText: "", // 构建出sql的解释
      operationList: [
        {label: "等于", value: "EQUAL"},
        {label: "不等于", value: "NOT_EQUAL"},
        {label: "包含字符", value: "IN"},
        {label: "不包含字符", value: "NOT_IN"},
        {label: "以...开头", value: "START"},
        {label: "不以...开头", value: "NOT_START"},
        {label: "以...结尾", value: "END"},
        {label: "不以...结尾", value: "NOT_END"},
        {label: "为空", value: "NULL"},
        {label: "不为空", value: "NOT_NULL"},
        {label: "空白", value: "BLANK"},
        {label: "非空白", value: "NOT_BLANK"},
        {label: "小于", value: "LESS_THAN"},
        {label: "大于", value: "MORE_THAN"},
      ],
      inquireType: 0,
      addFixCondition:false,
      addCommonlyCondition:false,
      saveCommonlyName:'',
      saveFixConditionName:'',
      renderContent: function (h, {node, data, store}) {
        let addElement = arguments[0];
        if (data.type === 'file') {
          return addElement('span', [
            addElement('i', {class: "iconfont icon-weibiaoti-_huabanfuben", style: "color: rgb(255,231,147)"}),
            addElement('span', "    "),
            addElement('span', arguments[1].node.label)
          ]);
        } else {
          return addElement('span', [
            addElement('i', {class: "el-icon-s-data", style: "color: rgb(117,120,225)"}),
            addElement('span', "    "),
            addElement('span', arguments[1].node.label)
          ]);
        }
      },
    }
  },
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val)
    },
    query (value) {
      this.queryArray = value
      console.log('queryArray', this.queryArray)
    },
    // 固定查询
    showQuery(val) {
      this.clearDialog(val);
    },
  },
  created () {
    this.getPersonnelStatus()
    this.getSex()
    this.getPositionLevel()
    this.getJobCategory()
    this.getSubset()
    this.getFixedCondition()
    this.getList()
    this.getAllDegree()
    this.getFixedConditions()
  },
  methods: {
    filterNode (value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    select (e) {
      this.$store.commit('changePersonnelStatus', e)
    },
    /**
     * 机构树点击
     */
    handleTreeNodeClick(e) {
      bus.$emit('sendBus', {id:e.uuid})
    },
    /**
     * 查询学历表
     */
    getAllDegree () {
      getAction('/opDictNew/findTreeByType?type=education')
          .then((res) => {
            if (res.code === 200) {
              this.recordRange = res.data
            }
          })
    },
    /**
     * 确定
     */
    handleRange() {
      this.departmentId =  this.$refs.TreeRange.getCheckedKeys()
      this.selectInstitutions = false
      let nameList = []
      this.$refs.TreeRange.getCheckedNodes().map(res=> {
        nameList.push(res.name)
      })
      this.textarea = nameList.join(',')
    },
    /** 根据id固定查询
     */
    async handleNodeClick () {
      const key = this.$refs.fixedCondition.getCurrentKey()
      if (!key || key === 'null1' || key === 'null2' || key === 'null3') return this.$message.warning({message: '请选择一个固定条件'})
      bus.$emit('sendBusFixed', {id:this.$refs.fixedCondition.getCurrentKey()})
    },
    /**
     * 删除固定条件
     */
    async handleNodeClickDelete(){
      let fixed_condition = this.$refs.fixedCondition.getCurrentKey()
      if (!fixed_condition || fixed_condition === 'null1'
          || fixed_condition === 'null2'
          || fixed_condition === 'null3') return this.$message.warning({message: '请选择删除对象'})
      this.$confirm('是否要删除这条数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(() => {
            postAction(opCondition.delete, { uuid: fixed_condition })
                .then((res) => {
                  if (res.code === 200) {
                    this.getFixedConditions()
                    this.$message({
                      type: 'success',
                      message: '删除成功!'
                    })
                    this.clickRow = null
                  } else {
                    this.$message({
                      type: 'warning',
                      message: res.msg
                    })
                  }
                })
          })
          .catch(() => {
            this.$refs.fixedCondition.setCurrentKey(null)
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
    },
    /**
     * 获取树部门数据
     */
    async getList(id) {
      const result = await getAction('/opDictNew/findTreeByType', { type:'rs_department' })
      if (result.code === 200) {
        this.data = result .data
      }
    },
    /**
     * 获取固定条件
     */
    async getFixedConditions() {
      this.data1 = [
        {
          uuid: 'null1',
          name: "基本信息类",
          type: 'file',
          children: []
        },
        {
          uuid: 'null2',
          name: "干部统计类",
          type: 'file',
          children: []
        },
        {
          uuid: 'null3',
          name: "其他类",
          type: 'file',
          children: []
        },
      ]
      const result = await postAction(opCondition.findAll,)
      if (result.code === 200) {
        result.data.map(res => {
          if(res.folder === 1) {
            this.data1[0].children.push(res)
          }else if(res.folder === 2){
            this.data1[1].children.push(res)
          }else if(res.folder === 3){
            this.data1[2].children.push(res)
          }else{
            this.data1.push(res)
          }
        })
        this.conditionList = JSON.parse(JSON.stringify(this.data1))
        this.commonlyList = result.data.filter(res => res.type === 2)
      }
    },
    /**
     * 获取所有子集
     */
    async getSubset () {
      const result = await postAction(opTableAll.opTableAllList)
      if (result.code === 200) {
        for (let i = 0; i < result.data.length; i++) {
          if (result.data[i].tableTxt.indexOf('子集') !== -1) {
            this.allSubset.push(result.data[i])
          }
        }
      }
    },
    /**
     * 模糊查询
     */
    startQuery() {
      if(!this.filterCondition) {
        this.conditionList = JSON.parse(JSON.stringify(this.data1))
      }else{
        postAction(opCondition.findByName, { name: this.filterCondition }).then(res=> {
          this.conditionList = res.data
        })
      }
    },
    /**
     * 选中的子集uuid
     */
    selectSubsetUuid (e) {
      if (e) {
        this.selectSubset = e
      }
      postAction('/opTableField/opTableFieldSearch', { tableUuid: this.selectSubset })
        .then(async (res) => {
          if (res.code === 200) {
            for (const item of res.data) {
              item.label = item.fieldTxt
              item.id = item.fieldName
              if (item.dictCode) {
                item.type = 'select'
                const choices = await this.getChoices(item.fieldName)
                console.log('choices', choices)
                item.choices = [{}]
              } else {
                item.type = item.type === 'STRING' ? 'text' : item.type === 'INT' ? 'text' : 'text'
              }
            }
            this.rules = res.data
          }
        })
    },
    /** 添加固定条件
     * */
    addFixedCondition(e) {
      this.inquireType = Number(e)
      this.showQuery = true
    },
    /** 修改固定条件
     * */
    handleModify() {
      const fixed_condition = this.$refs.fixedCondition.getCurrentNode()
      if (!fixed_condition || fixed_condition === 'null1'
          || fixed_condition === 'null2'
          || fixed_condition === 'null3') return this.$message.warning({message: '请选择编辑对象'})
      this.inquireType = fixed_condition.type
      const param = JSON.parse(fixed_condition.param)
      this.saveFixConditionName = fixed_condition.name
      this.sqlValue = param.sqlStr
      this.right = []
      param.list.forEach((res,index) => {
        this.selectContentByNameTable(res.type, res.code.toLowerCase())
        if(res.type === 'input' || res.type === 'radio' || res.type === 'date') {
          res.value = res.value.join(",")
        }
        if(res.type === 'number') {
          res.value = res.value[0]
        }
        let item_list = {
          fieldCode: res.code,
          fieldName: res.fieldName,
          type: res.type,
          operation: res.operation ? res.operation : '',
          value: res.value ? res.value : ''
        }
        this.right.push(item_list)
        this.showQuery = true
        this.isEitModify = true
      })
    },
    /**
     * 关闭查询框
     * */
    handleCloseInquire() {
      this.isEitModify = false
      this.showQuery = false
      this.saveFixConditionName = ''
      this.sqlValue = ''
      this.sqlValueText = ''
      this.right = []
    },
    /**
     * 获取所有选项
     * */
    async getChoices (code, table) {
      const result = await postAction(opCorePropertyValue.selectContentByNameTable, {
        value: code
      })
      console.log('choices', result)
      return result
    },
    /**
     * 开始查询
     */
    async startSql () {
      let national = ''
      let isNoPartyMember = ''
      let fullTime = ''
      if (this.national) {
        national = '1366935448091795458'
      }
      if (this.isNoPartyMember) {
        isNoPartyMember = '123'
      }
      if (this.fullTime) {
        fullTime = 'e772295f72e543698470433398e68ab9'
      }
      bus.$emit('sendBus', {
        ageMax: this.age2, //最大年龄
        ageMin: this.age1,  //最小年龄
        degreeMax: this.educationDown[this.educationDown.length-1], //最高学历
        degreeMin: this.educationUp[this.educationUp.length-1], //最低学历
        departmentList: this.departmentId, //机构id 数组
        educationType: fullTime, //全日制
        jobCategory: this.isJobCategory, //职务类别
        positionLevel: this.isPositionLevel, //职务级别
        national: national, // 少数民族
        isNoPartyMember: isNoPartyMember, // 非中共党员
        sex: this.gender, // 性别
        dataEnd:this.upperAge
      })
    },
    /**
     * 保存条件
     */
    saveBox () {
      let right_list = []
      if(this.departmentId.length) {}
      if(this.age1) {
        const item = {
          dict: '',
          fieldCode: "AGE",
          fieldName: "年龄",
          operation: "MORE_THAN",
          type: "number",
          value: [this.age1]
        }
        right_list.push(item)
      }
      if(this.age2) {
        const item = {
          dict: '',
          fieldCode: "AGE",
          fieldName: "年龄",
          operation: "LESS_THAN",
          type: "number",
          value: [this.age2]
        }
        right_list.push(item)
      }
      if(this.gender) {
        const item = {
          dict: "sex",
          fieldCode: "SEX",
          fieldName: "性别",
          operation: "EQUAL",
          type: "radio",
          value: this.gender.split(",")
        }
        right_list.push(item)
      }
      if(this.national) {
        const item = {
          dict: "national",
          fieldCode: "NATIONAL",
          fieldName: "民族",
          operation: "EQUAL",
          type: "radio",
          value: ["1366935448091795458"]
        }
        right_list.push(item)
      }
      if(this.isNoPartyMember) {
        const item = {
          dict: "rs_at",
          fieldCode: "RS_AT",
          fieldName: "政治面貌",
          operation: "EQUAL",
          type: "radio",
          value: ['123']
        }
        right_list.push(item)
      }
      if(this.isPositionLevel) {
        const item = {
          dict: "rs_zwcc",
          fieldCode: "RS_ZWCC",
          fieldName: "职务级别",
          operation: "EQUAL",
          type: "radio",
          value: this.isPositionLevel.split(",")
        }
        right_list.push(item)
      }
      if(this.isJobCategory) {
        const item = {
          dict: "rs_bq",
          fieldCode: "RS_BQ",
          fieldName: "职务类别",
          operation: "EQUAL",
          type: "radio",
          value: this.isJobCategory.split(",")
        }
        right_list.push(item)
      }
      if(this.educationUp) {
        const item = {
          dict: 'education',
          fieldCode: "EDUCATION",
          fieldName: "学历",
          operation: "MORE_THAN",
          type: "tree",
          value: this.educationUp[this.educationUp.length-1]
        }
        right_list.push(item)
      }
      if(this.educationDown) {
        const item = {
          dict: 'education',
          fieldCode: "EDUCATION",
          fieldName: "学历",
          operation: "LESS_THAN",
          type: "tree",
          value: this.educationDown[this.educationDown.length-1]
        }
        right_list.push(item)
      }
      if(this.fullTime) {
        const item = {
          dict: 'rs_jylb',
          fieldCode: "RS_JYLB",
          fieldName: "全日制",
          operation: "EQUAL",
          type: "radio",
          value: ['e772295f72e543698470433398e68ab9']
        }
        right_list.push(item)
      }
      if(this.upperAge) {
        const item = {
          dict: "",
          fieldCode: "BIRTHDAY",
          fieldName: "出生日期",
          num: 0,
          operation: "LESS_THAN",
          type: "date",
          value: [this.upperAge.substr(0,4) + '-' + this.upperAge.substr(4,2) + '-' + this.upperAge.substr(6,2)]
        }
        right_list.push(item)
      }
      this.sqlValue = ''
      right_list.map((res,index) => {
        this.sqlValue = (this.sqlValue + " @" + (index + 1) + " 并且").replace(
            /(^\s*)|(\s*$)/g,"")
      })
      this.sqlValue = this.sqlValue.substring(0,this.sqlValue.length-2).replace(
          /(^\s*)|(\s*$)/g,"")
      let item = {
        list: [],
        sqlStr: this.sqlValue,
      }
      right_list.map(res => {
        const conditionObj = {
          code: res.fieldCode,
          fieldName: res.fieldName,
          type: res.type,
          operation: res.operation ? res.operation : '',
          value: res.value
        }
        item.list.push(conditionObj)
      })
      this.$prompt('请输入保存条件名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        postAction(opCondition.insert, {
          name: value ,
          param: JSON.stringify(item),
          type: '2',
          folder: '0',
          baseCode: 'admin',
          createUser: 'admin'
        })
            .then((res) => {
              if (res.code === 200) {
                this.getFixedConditions()
                this.$message.success('保存成功')
              }
            })
      }).catch(() => {

      })
    },
    blurCheck() {
      var regDate =/(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))0229)/;
      var isDate = regDate.test(this.upperAge);
      if (!isDate) {
        this.$message.warning({message:'日期格式有误。请按YYYYMMdd格式填写'})
        this.upperAge = ''
        return;
      }
      console.log(this.upperAge)
    },
    /** 保存常用条件
     */
    handleSaveCondition(type) {
      if(!this.right.length) return this.$message.warning('请先选择指标')
      if(!this.sqlValue) return this.$message.warning('查询逻辑条件不能为空')
      this.commonlyType = type
      this.addCommonlyCondition = true
    },
    /** 引入常用条件
     */
    handleImportCondition(type) {
      this.commonlyType = type
      this.addCommonlyCondition = true
    },
    /** 保存
     */
    saveCommonly() {
      if (!this.saveCommonlyName) return this.$message.warning({message: '请输入常用条件名称'})
      let item = {
        list: [],
        sqlStr: this.sqlValue,
      }

      this.right.map(res => {
        const conditionObj = {
          code: res.fieldCode,
          fieldName: res.fieldName,
          type: res.type,
          operation: res.operation ? res.operation : '',
          value: typeof res.value === 'string'? res.value.split(",") :
              typeof res.value === 'number'? [res.value] :
                  typeof res.value === 'object'? [this.formateDate(res.value)] : res.value
        }
        item.list.push(conditionObj)
      })
      postAction(opCondition.insert, {
        name: this.saveCommonlyName ,
        param: JSON.stringify(item),
        type: 2,
        folder: '0',
        baseCode: 'admin',
        createUser: 'admin'
      })
          .then((res) => {
            if (res.code === 200) {
              this.getFixedConditions()
              this.$message.success('保存成功')
              this.saveCommonlyName = ''
            }
          })
    },
    /** 引入
     */
    importCommonly() {
      const fixed_condition = this.$refs.saveCommonly.getCurrentNode()
      if (!fixed_condition) return this.$message.warning({message: '请选择引入对象'})
      this.inquireType = fixed_condition.type
      const param = JSON.parse(fixed_condition.param)
      this.sqlValue = param.sqlStr
      this.right = []
      param.list.forEach((res,index) => {
        this.selectContentByNameTable(res.type, res.code.toLowerCase())
        if(res.type === 'input' || res.type === 'radio' || res.type === 'date') {
          res.value = res.value.join(",")
        }
        if(res.type === 'number') {
          res.value = res.value[0]
        }
        let item_list = {
          fieldCode: res.code,
          fieldName: res.fieldName,
          type: res.type,
          operation: res.operation ? res.operation : '',
          value: res.value ? res.value : ''
        }
        this.right.push(item_list)
      })
      this.$message.success('引入成功')
    },
    //关闭常用条件框
    closeCommonlyCondition() {
      this.addCommonlyCondition = false
      this.saveCommonlyName = ''
      this.$nextTick(() => {
        this.$refs.saveCommonly.setCurrentKey(null);
      })
    },
    /**
     * 清除条件
     */
    deleteBox() {
      this.departmentId = []
      this.textarea = ''
      this.age1 = ''
      this.age2 = ''
      this.gender = ''
      this.national = false
      this.isNoPartyMember = false
      this.isPositionLevel = ''
      this.isJobCategory = ''
      this.educationUp = ''
      this.educationDown = ''
      this.fullTime = false
      this.upperAge = ''

    },
    commonQuery () {
      this.str = ''
      const fuhao = this.queryArray.logicalOperator === 'any' ? ' or ' : ' and '
      this.digui(this.queryArray, 1, fuhao)
    },
    digui (data, type, fuhao) { // type  1：父级，2、子级别,
      let tiaojian = ''
      if (type === 1) {
        tiaojian = fuhao
        this.str += tiaojian
      } else {
        tiaojian = data.logicalOperator === 'any' ? ' or ' : ' and '
      }

      if (data.children) {
        for (let i = 0; i < data.children.length; i++) {
          let tiaojian1 = ''
          if (i !== 0) {
            tiaojian1 = data.logicalOperator === 'any' ? ' or ' : ' and '
          }
          if (data.children[i].query.children) { // 判断是否有子级
            if (i !== 0) {
              this.str += tiaojian
            }
            this.str += '( '
            this.digui(data.children[i].query, 2)
            this.str += ' )'
          } else {
            if (typeof (data.children[i].query.value) === 'object') { // 值为数组，说明值为多选
              if (data.children[i].query.value) {
                this.str += data.children[i].query.rule + ' in ( \'' + data.children[i].query.value.join('\',\'') + '\')'
              }
            } else {
              const operator = data.children[i].query.operator
              if (operator === '等于') {
                this.str += tiaojian1 + data.children[i].query.rule + ' = \'' + data.children[i].query.value + '\''
              } else if (operator === '不等于') {
                this.str += tiaojian1 + data.children[i].query.rule + ' !=\'' + data.children[i].query.value + '\''
              } else if (operator === '包含') {
                this.str += tiaojian1 + data.children[i].query.rule + ' like \\"%' + data.children[i].query.value + '%\\"'
              } else if (operator === '不包含') {
                this.str += tiaojian1 + data.children[i].query.rule + ' not like \\"%' + data.children[i].query.value + '%\\"'
              } else if (operator === '为空') {
                this.str += tiaojian1 + data.children[i].query.rule + ' = \\"\\"'
              } else if (operator === '不为空') {
                this.str += tiaojian1 + data.children[i].query.rule + ' != \\"\\"'
              } else if (operator === '以...开头') {
                this.str += tiaojian1 + data.children[i].query.rule + ' like \'' + data.children[i].query.value + '%\\"'
              } else if (operator === '以...结尾') {
                this.str += tiaojian1 + data.children[i].query.rule + ' like \\"%' + data.children[i].query.value + '%\''
              } else if (operator === '=' || operator === '<' || operator === '<=' || operator === '>' || operator === '>=') {
                this.str += tiaojian1 + data.children[i].query.rule + operator + '\'' + data.children[i].query.value + '\''
              } else if (operator === '<>') {
                this.str += tiaojian1 + data.children[i].query.rule + '!= \'' + data.children[i].query.value + '\''
              } else {
                this.str += tiaojian1 + data.children[i].query.rule + '= \'' + data.children[i].query.value + '\''
              }
            }
          }
        }
      }
      console.log('构造sql', this.str)
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {
        })
    },
    /**
     * 固定条件 树状右击事件
     */
    rightNodeClick (event, data) {
      const newChild = {
        id: 1,
        label: 'testtest',
        children: []
      }
      if (!data.children) {
        this.$set(data, 'children', [])
      }
      data.children.push(newChild)
    },
    /*
     * 获取人员状态字典
     */
    async getPersonnelStatus () {
      const result = await getAction('/opDictItem/getDictItemListByCode', {
        code: 'personnel_status'
      })
      this.PersonnelStatus = result.data.list
      if (this.$store.state.personnelStatus) {
        this.getStatus = this.$store.state.personnelStatus
      } else {
        this.getStatus = result.data.list[0].uuid
      }
      for (let j = 0; j < this.PersonnelStatus.length; j++) {
        this.PersonnelStatus[j].itemText = this.PersonnelStatus[j].itemText + '人员'
      }
    },
    /**
     * 获取性别列表
     */
    async getSex () {
      const result = await getAction(`${opDictNew.findByType}?type=sex`)
      this.sexDict = result.data
    },
    /**
     * 获取职务级别字典
     */
    async getPositionLevel () {
      const result = await getAction('/opDictNew/findTreeByType?type=rs_zwcc')
      this.positionLevel = result.data
    },

    /**
     * 获取职务类别字典
     */
    async getJobCategory () {
      const result = await getAction('/opDictNew/findTreeByType?type=rs_bq')
      this.jobCategory = result.data
    },
    /*
     * 获取固定条件
     */
    async getFixedCondition() {
      const result = await getAction(queryCondition.conditionsList)
      if (result.code === 200) {
        this.fixedConditionList = result.data
      }
    },
    /**
     * 根据选中固定条件
     */
    selectFixedCondition(e) {
      this.left = e.list
    },
    /**
     * 只允许选择一个字段
     */
    handleLeftCheckbox(e) {
      if (this.checkedLeft.length > 1) {
        this.checkedLeft.splice(0, 1)
      }
    },
    /**
     * 删除全部
     */
    delAll() {
      this.right = [];
      this.checkedRight = [];
      this.statisticalName = ''
      this.sqlValue = ''
      this.sqlValueText = ''
    },
    /**
     * 右箭头
     */
    toRight() {

        if (!this.checkedLeft.length) return this.$message.warning({message: '请选择一个选项'})
        // this.right = this.handleConcatArr(this.right, this.checkedLeft);
        this.right.push(JSON.parse(JSON.stringify(this.checkedLeft[0])))
        this.right[this.right.length - 1].num = this.right.length - 1
      if (this.right[this.right.length - 1].type === 'radio' || this.right[this.right.length - 1].type === 'tree') {
        this.selectContentByNameTable(this.right[this.right.length - 1].type, this.right[this.right.length - 1].dict)
      }
    },
    /**
     * 左箭头
     */
    toLeft() {
      let list = [];
      for (const item of this.checkedRight) {
        if (this.right[item]) {
          list.push(this.right[item]);
        } else {
          list.push(item);
        }
      }
      this.right = this.right.concat(list).filter((v, i, arr) => {
        return arr.indexOf(v) === arr.lastIndexOf(v);
      })
      this.checkedRight = [];
    },
    /**
     * 依据字典name查下拉选或依据表名table查树状所有的数据
     */
    selectContentByNameTable(type, dict) {
      if (type === 'radio') {
        getAction(opDictNew.findByType, {
          type: dict
        }).then(res => {
          this.$set(this.right[this.right.length - 1], 'inquire', res.data);
        })
      } else if (type === 'tree') {
        getAction('/opDictNew/findTreeByType', {
          type: dict
        }).then(res => {
          this.$set(this.right[this.right.length - 1], 'inquire', res.data);
        })
      }
    },
    /**
     * checkBox单选
     */
    singleChoice(i,item) {
      if(!item.operation || !item.value) return this.$message.warning('请确认信息是否填写')
      this.checkedRight = [];
      this.checkedRight.push(this.right[i]);
      this.sqlValue = (this.sqlValue + " @" + (i + 1)).replace(
              /(^\s*)|(\s*$)/g,
              ""
      );
      const filter_operation = this.operationList.find(res => res.value === item.operation)
      const filter_inquire = (item.type === "radio" || item.type === "tree" )? item.inquire.find(res => res.uuid === item.value) : { name:item.value }
      this.sqlValueText = (`${this.sqlValueText} ${item.fieldName + filter_operation.label}'${filter_inquire.name}'`).replace(
          /(^\s*)|(\s*$)/g,
          ""
      );
    },
    /**
     * 构建sql查询
     */
    createSql(i) {
      if (i === 1) {
        this.sqlValue = (this.sqlValue + " 并且").replace(/(^\s*)|(\s*$)/g, "");
        this.sqlValueText = (this.sqlValueText + " 并且").replace(/(^\s*)|(\s*$)/g, "");
      } else if (i === 2) {
        this.sqlValue = (this.sqlValue + " 或者").replace(/(^\s*)|(\s*$)/g, "");
        this.sqlValueText = (this.sqlValueText + " 或者").replace(/(^\s*)|(\s*$)/g, "");
      } else if (i === 3) {
        this.sqlValue = (this.sqlValue + " (").replace(/(^\s*)|(\s*$)/g, "");
        this.sqlValueText = (this.sqlValueText + " (").replace(/(^\s*)|(\s*$)/g, "");
      } else {
        this.sqlValue = (this.sqlValue + ")").replace(/(^\s*)|(\s*$)/g, "");
        this.sqlValueText = (this.sqlValueText + ")").replace(/(^\s*)|(\s*$)/g, "");
      }
    },
    /**
     * 清空dialog的数据
     */
    clearDialog(val) {
      if (!val) {
        this.left = [];
        this.right = [];
        this.subsetUuid = "";
        this.checkedLeft = [];
        this.checkedRight = [];
        this.timeSetting = false;
        this.sqlValue = "";
        this.statisticalName = "";
        this.radio = 'SUM';
        this.time = "";
        this.operation = "";
      }
    },
    /**
     * 固定条件查询
     */
    fixedConditionSearch(){
      if (!this.right.length) return this.$message.warning({message: '请选择指标项'})
      if(this.inquireType === 0) {
        this.sqlValue = ''
        this.right.map((res,index) => {
          this.sqlValue = (this.sqlValue + " @" + (index + 1) + " " + this.easyCondition).replace(
              /(^\s*)|(\s*$)/g,"")
        })
        this.sqlValue = this.sqlValue.substring(0,this.sqlValue.length-2).replace(
            /(^\s*)|(\s*$)/g,"")
      }
      if(this.inquireType === 1) {
        if (!this.sqlValue) return this.$message.warning({message: '请输入公式表达式'})
      }
      let item = {
        list: [],
        sqlStr: this.sqlValue,
      }

      this.right.map(res => {
        const conditionObj = {
          code: res.fieldCode,
          fieldName: res.fieldName,
          type: res.type,
          operation: res.operation ? res.operation : '',
          value: typeof res.value === 'string'? res.value.split(",") :
                  typeof res.value === 'number'? [res.value] :
                          typeof res.value === 'object'? [this.formateDate(res.value)] : res.value
        }
        item.list.push(conditionObj)
      })
      bus.$emit('sendBusFixed', {list: item.list,sqlStr: item.sqlStr,isisFixedCondition: true})
      this.showQuery = false
    },
    //日期转化
    formateDate(data) {
      let year = data.getFullYear()
      let month = data.getMonth() + 1
      let day = data.getDate()
      let hh = data.getHours()
      let dd = data.getMinutes()
      let mm = data.getSeconds()
      if (month < 10) month = '0' + month
      if (day < 10) day = '0' + day
      if (hh < 10) hh = '0' + hh
      if (dd < 10) dd = '0' + dd
      if (mm < 10) mm = '0' + mm
      return year + '-' + month + '-' + day + " " + hh + ':' + dd + ':' + mm
    },
    /**
     * 循环的el-select 强制刷新视图
     */
    selectSet(index) {
      this.$set(this.right, index, this.right[index]);
    },
    //数字类型判断
    leaveJudgment(index) {
      if (typeof this.right[index].value !== 'number') {
        this.right[index].value = ''
      }
    },
    /**
     * 保存固定查询条件
     */
    fixedConditionSave(){
      if (!this.right.length) return this.$message.warning({message: '请选择指标项'})
      if(this.inquireType === 0) {
        this.sqlValue = ''
        this.right.map((res,index) => {
          this.sqlValue = (this.sqlValue + " @" + (index + 1) + " " + this.easyCondition).replace(
              /(^\s*)|(\s*$)/g,"")
        })
        this.sqlValue = this.sqlValue.substring(0,this.sqlValue.length-2).replace(
            /(^\s*)|(\s*$)/g,"")
      }
      if(this.inquireType === 1) {
        if (!this.sqlValue) return this.$message.warning({message: '请输入公式表达式'})
      }
      this.addFixCondition = true
    },
    /**
     * 关闭保存固定查询条件
     */
    addFixConditionClose(){
      this.addFixCondition = false
      this.saveFixConditionName = ''
      this.$nextTick(() => {
        this.$refs.saveStatistics.setCurrentKey(null);
      })
    },
    /**
     * 确定保存固定查询条件
     */
    FixConditionConfirm(){
      if (!this.saveFixConditionName) return this.$message.warning({message: '请输入条件名称'})
      let save_statistics = this.$refs.saveStatistics.getCurrentKey()
      let item = {
        list: [],
        sqlStr: this.sqlValue,
      }

      this.right.map(res => {
        const conditionObj = {
          code: res.fieldCode,
          fieldName: res.fieldName,
          type: res.type,
          operation: res.operation ? res.operation : '',
          value: typeof res.value === 'string'? res.value.split(",") :
                  typeof res.value === 'number'? [res.value] :
                          typeof res.value === 'object'? [this.formateDate(res.value)] : res.value
        }
        item.list.push(conditionObj)
      })
      if(this.isEitModify) {
        postAction(opCondition.update, {
          name: this.saveFixConditionName ,
          param: JSON.stringify(item),
          type: this.inquireType,
          folder: this.$refs.fixedCondition.getCurrentNode().folder,
          uuid: this.$refs.fixedCondition.getCurrentNode().uuid,
          baseCode: 'admin',
          updateUser: 'admin'
        })
            .then((res) => {
              if (res.code === 200) {
                this.getFixedConditions()
                this.$message.success('更改成功')
              }
              this.isEitModify = false
            })
      }else{
        postAction(opCondition.insert, {
          name: this.saveFixConditionName ,
          param: JSON.stringify(item),
          type:this.inquireType,
          folder:!save_statistics ? '0' :
              save_statistics === 'null1' ? '1' :
                  save_statistics === 'null2' ? '2' :
                      save_statistics ? '3' : '0',
          baseCode: 'admin',
          createUser: 'admin'
        })
            .then((res) => {
              if (res.code === 200) {
                this.getFixedConditions()
                this.$message.success('保存成功')
              }
            })
      }
      this.addFixCondition = false
    },
    /**
     * 删除固定查询条件
     */
    DeleteFixCondition(type){
      let save_statistics = this.$refs[type].getCurrentKey()
      if (!save_statistics || save_statistics === 'null1'
          || save_statistics === 'null2'
          || save_statistics === 'null3') return this.$message.warning({message: '请选择删除对象'})
      this.$confirm('是否要删除这条数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(() => {
            postAction(opCondition.delete, { uuid: save_statistics })
                .then((res) => {
                  if (res.code === 200) {
                    this.getFixedConditions()
                    this.$message({
                      type: 'success',
                      message: '删除成功!'
                    })
                    this.clickRow = null
                  } else {
                    this.$message({
                      type: 'warning',
                      message: res.msg
                    })
                  }
                })
          })
          .catch(() => {
            this.$refs.fixedCondition.setCurrentKey(null)
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
    }
  }
}
</script>
<style>
.btn-secondary, .form-control {
  height: 30px !important;
  line-height: 30px !important;
  padding: 0 5px;
  font-size: 15px;
}

.form-inline {
  padding: 5px 10px;
}

.vqb-group {
  margin-top: 10px;
  border: 1px solid #0063c7;
}

.vqb-group-heading {
  background-color: #0063c7;
  color: #ffffff;
}

.vqb-children {
  padding: 10px;
}

.vqb-rule {
  margin-top: 5px;
}

.btn-secondary {
  background-color: #0063c7;
  border: none;
}
</style>
<style lang="less" scoped>
.department-tree {
  max-height: 280px;
  overflow: auto;
  .show-ellipsis {
    width: 200px;
    overflow: auto;
    font-size: 14px;

  }

  .el-tree-node__content {
    display: block;
    width: 100%;
    overflow: auto;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}

.tate-picker {
  width: 100% !important;
}
.popover {
  padding: 5px 10px;
  background-color: dimgrey;
  color: white;
}

.btn_group {
  width: 100%;
  display: flex;
  justify-content: space-evenly;
  margin-top: 10px;

  .btn_item {
    flex: 1;
    margin: 0 4px;
  }
}
.individual_line {
  border: 1px solid #eee;
  padding-left: 30px;
  position: relative;
  margin-top: 20px;
  height: 112px;
  display: flex;
  align-items: center;
}

.individual_title {
  display: inline-block;
  background: #fff;
  position: absolute;
  padding: 0 5px;
  top: -12px;
  left: 15px;
  font-weight: 600;
  color: #15428b;
  letter-spacing: 1px;
}
.sql_tree {
  // padding: 0 10px;
  .sql_item {
    font-size: 14px;
    margin-top: 15px;

    .flex_bet {
      display: flex;
      justify-content: space-between;

      .sql_type {
        font-weight: 700;
      }
    }

    .border_line {
      border: 1px solid rgba(215, 215, 215, 1);
      border-radius: 4px;
      padding: 15px 0;
      text-align: center;

      .mini_select {
        width: 45px;
        height: 30px;
      }
    }
  }
}
::v-deep .el-textarea__inner {
  color: #000000!important;
}
.mini_select /deep/ .el-input__inner {
  padding: 8px !important;
}
.schedule /deep/ .el-input__inner {
  height: 28px;
  line-height: 28px;
}
.mini_select /deep/ .el-input__suffix {
  right: -2px;
}

.sql_tree /deep/ .el-input--mini .el-input__inner {
  height: 24px;
  line-height: 24px;
}

.sql_tree /deep/ .el-input__suffix {
  top: 2px;
}

.radio_item {
  margin-right: 5px;
}

.radio_item /deep/ .el-radio__label {
  padding-left: 3px;
  font-size: 12px;
}

.ft13 {
  font-size: 13px;
}

.select_btn /deep/ .we-button[data-v-3c390a53] {
  background-color: #0063c7 !important;
}

.col_h_b {
  height: 472px;
  border: 1px solid #eee;
  border-radius: 5px;
  margin-top: 10px;
  overflow-y: auto;
  padding-left: 10px;
}

.line_h {
  line-height: 30px;
}

.text_one_row {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
</style>
